package net.weamor.ichat.api.action;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import net.weamor.ichat.cim.push.DefaultMessagePusher;
import net.weamor.ichat.cim.push.SystemMessagePusher;
import net.weamor.ichat.common.util.Constants;
import net.weamor.ichat.common.util.ContextHolder;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.aspectj.util.FileUtil;
import org.springframework.web.bind.ServletRequestBindingException;

import com.farsunset.cim.nio.mutual.Message;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 
 * @ClassName MessageAction  
 * @Description 消息处理action 
 * @author weamor@163.com 
 * @date 2015-5-11  
 *   
 */
public class MessageAction extends ActionSupport implements
		ModelDriven<Message> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Message message = new Message();
	private File file; //上传的文件
	private String fileName;
	private String saveName;
    

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getSaveName() {
		return saveName;
	}

	public void setSaveName(String saveName) {
		this.saveName = saveName;
	}

	/**
	 * 关于http参数获取，  struts2  的模型驱动  比如 http 参数 sender=xiaomao&receiver=xiaogou
	 * struts自动会将参数的值 存入getModel()返回的对象的对应属性中，即xiaomao会存入message.sender属性,xiaogou会存入message.receiver属性
	 * 省去了request.getParameter("sender")方式获取参数，，如果参数名在getModel()返回的对象中不存在，则需要用request.getParameter()获取
	 * 其他相关*Action.java中 同理，这里做统一说明!
	 */
	public String send() throws Exception {

		HashMap<String, Object> datamap = new HashMap<String, Object>();
		HashMap<String, String> data = new HashMap<String, String>();
		ServletActionContext.getResponse().setContentType(
				"text/json;charset=UTF-8");
		datamap.put("code", 200);

		try {

			checkParams();
			
			String realpath = ServletActionContext.getServletContext().getRealPath("/images");
			
			HttpServletRequest request = ServletActionContext.getRequest();
			//项目的基础路径
			String BasePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
			
			//固定了文件下载
	        message.setFile(BasePath+"/images/6e397233eb4330492ce44268748cae74.jpg");
	        message.setFileType(".jpg");
	        System.out.println("要发送的message:"+message);
	        
	        
	        
			if (Constants.MessageType.TYPE_2.equals(message.getType())) {
				// 向客户端 发送消息
				ContextHolder.getBean(SystemMessagePusher.class).pushMessageToUser(message);
				
			} else {
				// 向客户端 发送消息
				ContextHolder.getBean(DefaultMessagePusher.class)
						.pushMessageToUser(message);
			}

			data.put("id", message.getMid());
			data.put("createTime", String.valueOf(message.getTimestamp()));
			datamap.put("data", data);
		} catch (Exception e) {
			datamap.put("code", 500);
			e.printStackTrace();
		}

		ServletActionContext.getResponse().getWriter().print(
				new Gson().toJson(datamap));
		return null;
	}
	
	/**
	 * 给客户端发送文件
	 * 首先要服务器将文件传递到服务器，然后将服务器的地址发送给客户端，客户端实现断点下载即可
	 * @return
	 * @throws Exception
	 */
	public String sendFile() throws Exception {

		HashMap<String, Object> datamap = new HashMap<String, Object>();
		HashMap<String, String> data = new HashMap<String, String>();
		ServletActionContext.getResponse().setContentType(
				"text/json;charset=UTF-8");
		datamap.put("code", 200);

		try {

			checkParams();

			if (Constants.MessageType.TYPE_2.equals(message.getType())) {
				// 向客户端 发送消息
				ContextHolder.getBean(SystemMessagePusher.class).pushMessageToUser(message);
				
			} else {
				// 向客户端 发送消息
				ContextHolder.getBean(DefaultMessagePusher.class)
						.pushMessageToUser(message);
			}

			data.put("id", message.getMid());
			data.put("createTime", String.valueOf(message.getTimestamp()));
			datamap.put("data", data);
		} catch (Exception e) {
			datamap.put("code", 500);
			e.printStackTrace();
		}

		ServletActionContext.getResponse().getWriter().print(
				new Gson().toJson(datamap));
		return null;
	}

	/**
	 * 文件由客户端发往阿里云 OSS 存储
	 * @param messageServiceImpl
	 */
	private void fileHandler(Message mo, HttpServletRequest request)
			throws IOException {
		if (request instanceof MultiPartRequestWrapper) {
			MultiPartRequestWrapper pr = (MultiPartRequestWrapper) request;
			if (pr.getFiles("file") != null) {
				File file = pr.getFiles("file")[0];

				String fileType = request.getParameter("fileType");
				// String dir = dirMap.get(fileType);
				// TODO 这里是文件路径
				String dir = "";
				if (StringUtils.isEmpty(dir)) {
					throw new IllegalArgumentException("fileType:" + fileType
							+ " 未定义");

				}
				String path = request.getSession().getServletContext()
						.getRealPath(dir);
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				File des = new File(path + "/" + uuid);
				FileUtil.copyFile(file, des);
				mo.setFile(dir + "/" + uuid);
				mo.setFileType(fileType);
			}
		}
	}

	/**
	 * 检查参数
	 * @Title: checkParams 
	 * @throws ServletRequestBindingException 参数说明
	 * @throws
	 */
	private void checkParams() throws ServletRequestBindingException {
		if (StringUtils.isEmpty(message.getReceiver())) {
			throw new IllegalArgumentException("receiver 不能为空!");

		}
	}

	@Override
	public Message getModel() {
		// TODO Auto-generated method stub
		return message;
	}

	
	

}
